#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/msg.h>

#define MAXMSG  (8192+sizeof(long))

struct msgbuf {
    long mtype;
    char mtext[1];
};

int main(int argc, char *argv[])
{
    int c, flag, mqid;
    long type;
    ssize_t n;
    struct msgbuf *buf;

    type = flag = 0;

    while ((c = getopt(argc, argv, "nt:")) != -1)
    {
        switch(c)
        {
            case 'n':
                flag |= IPC_NOWAIT;
                break;
            case 't':
                type = atol(optarg);
                break;
        }
    }
    
    if (optind != argc -1)
    {
        printf("usage: %s [-n][-t type]<pathname>\n", argv[0]);
        exit(0);
    }

    if ((mqid = msgget(ftok(argv[optind], 0), 0000)) == -1)
    {
        perror("msgget error");
        exit(0);
    }

    buf = malloc(MAXMSG);
    if ((n = msgrcv(mqid, buf, MAXMSG, type, flag)) < 0)
    {
        perror("msgrcv error");
        exit(0);
    }

    printf("read %d bytes, type=%ld\n", n, buf->mtype);

    return 0;
}
